import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { message, Skeleton, Radio } from 'antd'
import ReactEchartsCore from 'echarts-for-react/lib/core'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import { TitleComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import style from './Style.module.less'
import { addResizeEvent, delResizeEvent } from '@redux/actions'
import { colors } from '@js/config'
import { strToNum } from '@src/assets/js/tool'
echarts.use([PieChart, TitleComponent, CanvasRenderer])
const ForeignMap = {
  涉港澳台案件: {
    party_area_tag: ['港', '澳', '台']
  },
  涉外案件: {
    party_area_tag: ['外国']
  },
  其他案件: {
    party_area_tag: ['本地', '一方外地', '双方外地']
  }
}

class ForeignStatistic extends Component {
  state = {
    colors,
    list: [],
    total: 0,
    ready: true,
    type: 'casenum',
    totalData: null
  }

  getPercent (v) {
    const { total } = this.state
    if (v && total) {
      return Math.round(v / total * 10000) / 100 + '%'
    }
  }

  // 转换单位
  transferUnit (v) {
    if (v > 100000000) {
      return Math.round(v / 1000000) / 100 + '亿'
    }
    if (v > 10000) {
      return Math.round(v / 100) / 100 + '万'
    }
    return v
  }

  changeType (type) {
    const list = this.state.totalData[type]
    this.setState({
      type,
      list,
      total: list.reduce((a, b) => ({ value: strToNum(a.value) + strToNum(b.value) })).value
    })
  }

  // 获取数据
  getData () {
    this.setState({ loading: true })
    this.$get('/api/xapc/casestat/statAreaForeign', {
      condition: this.props.condition
    }).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        const data = this.formatData(res.data)
        const d = data[this.state.type]
        this.setState(d, () => {
          this.props.onChange(data)
        })
      } else {
        message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 格式化数据
  formatData (data) {
    const typeKeys = Object.keys(data)
    const d = {}
    typeKeys.forEach(type => {
      const list = data[type]
      d[type] = {
        totalData: data,
        list,
        total: list.reduce((a, b) => ({ value: strToNum(a.value) + strToNum(b.value) })).value
      }
    })
    return d
  }

  // 渲染全部数量文本
  renderTotalStr () {
    const { total } = this.state
    if (this.state.type === 'casenum') {
      return `${total}件`
    } else {
      return `${this.transferUnit(total)}元`
    }
  }

  // 渲染类型
  renderTypeStr () {
    if (this.state.type === 'casenum') {
      return '案件数'
    } else {
      return '案件标的'
    }
  }

  // 获取配置
  getOptions () {
    return {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        show: false
      },
      series: [
        {
          name: '立案情况',
          type: 'pie',
          radius: ['50%', '70%'],
          itemStyle: {
            borderWidth: 5,
            borderType: 'solid',
            borderColor: 'rgba(255, 255, 255, 1)'
          },
          label: {
            show: false,
            position: 'center',
            formatter: `{a|${this.renderTypeStr()}}\n{b|${this.renderTotalStr()}}`,
            rich: {
              a: {
                color: '#7E889C',
                lineHeight: 20,
                fontSize: 16
              },
              b: {
                color: '#1F2229',
                lineHeight: 40,
                fontSize: 24
              }
            }
          },
          data: this.state.list.map((li, i) => {
            const d = {
              ...li,
              itemStyle: {
                color: this.state.colors[i]
              }
            }
            if (i === 0) {
              d.label = {
                show: true
              }
            }
            return d
          })
        }
      ]
    }
  }

  // 点击表格前往详情
  chartClickHandle (e) {
    const { formData } = this.props
    this.props.addWindow({ id: 'AllCaseManage', title: '全委案件', componentName: 'AllCaseManage', forceRefresh: true, meta: { formData: { ...formData, ...ForeignMap[e.name] } } })
  }

  componentDidUpdate (prev) {
    if (prev.searchVersion !== this.props.searchVersion) {
      this.getData()
    }
  }

  componentDidMount () {
    this.getData()
    this.props.addResizeEvent({
      name: 'foreignStatistic',
      handle: () => this.setState({ ready: false }, () => {
        setTimeout(() => {
          this.setState({ ready: true })
        }, 100)
      })
    })
  }

  componentWillUnmount () {
    this.props.delResizeEvent('foreignStatistic')
  }

  // 渲染选择列表
  renderList () {
    return this.state.list.map((li, i) => {
      const p = this.getPercent(li.value)
      return (
        <li className={style.li} key={i}>
          <span className={style['li-title']}>
            <span className={style['li-tag']} style={{ backgroundColor: this.state.colors[i] }} />
            <span className={style['li-title__text']}>{li.name}</span>
          </span>
          <span className={style['li-value']}>
            <span className={style['li-value__percent']}>{p}</span>
            <span className={style['li-value__split']} />
            <span className={style['li-value__text']}>{this.transferUnit(li.value)}</span>
          </span>
        </li>
      )
    })
  }

  render () {
    const onEvents = { click: this.chartClickHandle.bind(this) }
    return (
      <div className={style.block}>
        <div className={style['block-header']}>
          <span className={style['block-header__title']}>{this.props.year}涉外涉港澳台案件情况</span>
          <Radio.Group onChange={e => this.changeType(e.target.value)} value={this.state.type}>
            <Radio.Button value='casenum'>数量占比</Radio.Button>
            <Radio.Button value='disputeamount'>标的占比</Radio.Button>
          </Radio.Group>
        </div>
        <div className={style['block-body']}>
          <Skeleton loading={this.state.loading}>
            <div className={style['chart-box']}>
              {this.state.ready ? <ReactEchartsCore style={{ width: '100%', height: '100%' }} echarts={echarts} onEvents={onEvents} option={this.getOptions()} /> : null}
            </div>
            <div className={style['list-box']}>
              <ul className={style.list}>
                {this.renderList()}
              </ul>
            </div>
          </Skeleton>
        </div>
      </div>
    )
  }
}

ForeignStatistic.propTypes = {
  condition: PropTypes.string,
  formData: PropTypes.object,
  searchVersion: PropTypes.number,
  onChange: PropTypes.func
}
ForeignStatistic.defaultProps = {
  condition: JSON.stringify([]),
  formData: undefined,
  searchVersion: Date.now(),
  onChange: () => {}
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addResizeEvent: i => dispatch(addResizeEvent(i)),
    delResizeEvent: i => dispatch(delResizeEvent(i))
  }
})

export default connect(mapState, mapDispatch)(ForeignStatistic)
